const newsModel = require('../model/news');
const { newsList } = require('../services/news');
const { saveSqlParse, updateSqlParse, saveAllSqlParse } = require('../common/utils');
const { connect } = require("../model/index");

/**
 * 获取文章列表
 * @method: get
 * @param {*} ctx
 * @param {*} next
 */
const getNewsList = async (ctx, next) => {
  const query = ctx.request.body;
  const pageSize = Number(query.pageSize || 10);
  const pageNum = Number(query.pageNum || 1) - 1;

  const queryParams = query.params || {};
  const { list, pageCount, total } = await newsList(queryParams, {
    pageSize,
    pageNum
  });
  ctx.body = {
    data: {
      datas: list,
      pageNum: pageNum + 1,
      pageSize: pageSize,
      pageCount: pageCount,
      total: total,
    },
    code: 200,
    msg: '查询成功',
  };
  await next();
};

/**
 * 添加文章
 * @method: post
 * @param {*} ctx
 * @param {*} next
 */
const addNews = async (ctx, next) => {
  const query = ctx.request.body;
  const saveData = {
    title: query.title,
    description: query.description,
    content: query.content,
    cover_image: query.cover_image,
    admin_user_id: query.admin_user_id, // 上架人
    create_time: Math.floor(Date.now() / 1000),
    update_time: Math.floor(Date.now() / 1000),
  };

  const { fields, values } = saveSqlParse(saveData);

  const database = newsModel.TABLE_NAME;
  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    const [rows, field] = await connection.query(
      `
        INSERT INTO ${database}
        (${fields.join(',')})
        VALUES (${values.join(',')})
      `
    );

    await connection.commit();
  } catch (err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }

  ctx.body = {
    data: null,
    code: 200,
    msg: '操作成功',
  };
  await next();
};

/**
 * 修改文章
 * @method: post
 * @param {*} ctx
 * @param {*} next
 */
const updateNews = async (ctx, next) => {
  const query = ctx.request.body;
  const id = query.id;
  const saveData = {
    title: query.title,
    description: query.description,
    content: query.content,
    cover_image: query.cover_image,
    update_time: Math.floor(Date.now() / 1000),
  };

  const sqlArr = updateSqlParse(saveData);

  const database = newsModel.TABLE_NAME;
  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    await connection.query(
      `
        UPDATE ${database}
        SET ${sqlArr.join(',')}
        WHERE id = ?
      `,
      [Number(id)]
    );

    await connection.commit();
  } catch (err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }

  ctx.body = {
    data: {},
    code: 200,
    msg: '操作成功',
  };
  await next();
};

/**
 * 获取文章详情
 * @method: get
 * @param {*} ctx
 * @param {*} next
 */
const newsById = async (ctx, next) => {
  const query = ctx.request.query;
  const id = query.id;

  let res = {};
  const database = newsModel.TABLE_NAME;
  let [rows, fields] = await connect.query(`select id,title,description,content,cover_image from ${database} where status = ? and id = ?`, [
    1,
    id,
  ]);
  if (rows[0]) {
    res = rows[0];

    let [prevList] = await connect.query(`select * from ${database} where id=(select max(id) from ${database} where id<?) and status = ?`, [
      id,
      1,
    ]);
    let [nextList] = await connect.query(`select * from ${database} where id=(select max(id) from ${database} where id>?) and status = ?`, [
      id,
      1,
    ]);
    res.prev = prevList[0] || null;
    res.next = nextList[0] || null;
  }

  ctx.body = {
    data: res,
    code: 200,
    msg: '查询成功',
  };
  await next();
};

/**
 * 删除文章
 * @method: get
 * @param {*} ctx
 * @param {*} next
 */
const deleteNewsById = async (ctx, next) => {
  const query = ctx.request.query;
  const id = query.id;

  const database = newsModel.TABLE_NAME;
  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    await connection.query(
      `
        DELETE FROM ${database}
        where id = ?
      `,
      [id]
    );
    await connection.commit();
  } catch(err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }

  ctx.body = {
    data: {},
    code: 200,
    msg: '操作成功',
  };
  await next();
};

module.exports = {
  getNewsList,
  addNews,
  updateNews,
  newsById,
  deleteNewsById
}